﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;
using Ice.Toolkit.Data.Entity;
using Ice.Toolkit.Data.ILInvoker;
using System.Reflection;

namespace Ice.Toolkit.Data.Sql
{
    internal class InsertBuilder<T> : BuilderBase<T> where T : EntityBase<T>, new()
    {
        private String _sqlString = "INSERT INTO [{0}] ({1}) VALUES ({2})";
        private T _instance;

        public InsertBuilder(T instance, DataContext context) : base(context)
        {
            _instance = instance;
        }

        //public static Func<T, object> CreateGetPropertyValueFunc(PropertyInfo property)
        //{
        //    //var property = typeof(T).GetProperty("Name");
        //    var target = Expression.Parameter(typeof(object));
        //    var castTarget = Expression.Convert(target, typeof(T));
        //    var getPropertyValue = Expression.Property(castTarget, property);
        //    var castPropertyvalue = Expression.Convert(getPropertyValue, typeof(object));
        //    return Expression.Lambda<Func<object, object>>(castPropertyvalue, target).Compile();
        //}

        public override String Build()
        {
            if (String.IsNullOrEmpty(SQLText))
            {
                var textField = String.Empty;
                var textParam = String.Empty;

                var columns = EntityAttribManager.Get<T>().Columns;
                var t = typeof(T);
                foreach (var col in columns)
                {
                    textField += "[" + col.Value.DbColumn + "], ";
                    textParam += "@" + col.Value.DbColumn + ", ";
                    AddParameter(col.Key, t.GetProperty(col.Key).GetValue(_instance, null));
                }

                textField = RemoveTail(textField, ",");
                textParam = RemoveTail(textParam, ",");

                var table = EntityAttribManager.Get<T>().Talbe;

                SQLText = String.Format(_sqlString, table.TableName, textField, textParam);
            }

            return SQLText;
        }
    }
}
